package com.buss.admin.controller;

import com.buss.admin.entity.AdminEntity;
import com.buss.admin.service.IFileService;
import com.buss.admin.service.IFileUserService;
import com.buss.admin.trans.form.AdminMemberForm;
import com.buss.admin.trans.form.HXUserForm;
import com.buss.admin.trans.form.MemberForm;
import com.buss.common.entity.HxFile;
import com.buss.common.entity.HxFileUser;
import com.buss.common.model.json.EasyUIDataGridResult;
import com.buss.common.model.json.HXResult;
import com.buss.common.service.SysServiceI;
import com.buss.common.trans.vo.FileVo;
import com.buss.member.entity.GeneralUserEntity;
import com.buss.member.service.IMemberService;
import com.buss.member.util.StatusCode;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.jweb.core.bean.PageMode;
import org.jweb.core.query.hibernate.qbc.CriteriaQuery;
import org.jweb.core.util.MyBeanUtils;
import org.jweb.core.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/admin/member")
public class AdminMemberController {

	@Autowired
	private IMemberService memberService;

	@Autowired
	private SysServiceI sysService;

	/*
	 * 查询所有会员列表并分页
	 */
	@RequestMapping("/list")
	@ResponseBody
	public EasyUIDataGridResult getMemberList(MemberForm searchForm) {

		// 分页查询
		CriteriaQuery cq = searchForm.getCriteriaQuery();

		int pageNo = Integer.parseInt(searchForm.getPage());
		int pageSize = Integer.parseInt(searchForm.getRows());

		// 定义返回数据格式
		EasyUIDataGridResult result = new EasyUIDataGridResult();
		PageMode<GeneralUserEntity> pageMode = memberService.list4page(cq, pageNo, pageSize);

		// 封装数据
		result.setRows(pageMode.getResult());
		result.setTotal(pageMode.getTotal());

		return result;

	}

	/*
	 * 查询所有会员列表并分页
	 */
	@RequestMapping("/chckelist")
	@ResponseBody
	public EasyUIDataGridResult getCheckMemberList(MemberForm searchForm){

		// 分页查询
		CriteriaQuery cq = searchForm.getCriteriaQuery();

		/*
		 * 设置查询条件
		 */
		// cq.add(Restrictions.sizeGe("checkstatus", 10));
		// cq.add(Restrictions.ge("checkstatus", 10));

		int pageNo = Integer.parseInt(searchForm.getPage());
		int pageSize = Integer.parseInt(searchForm.getRows());

		// 定义返回数据格式
		EasyUIDataGridResult result = new EasyUIDataGridResult();
		PageMode<GeneralUserEntity> pageMode = memberService.list4page(cq, pageNo, pageSize);

		// 封装数据
		result.setRows(pageMode.getResult());
		result.setTotal(pageMode.getTotal());

		return result;

	}

	/**
	 * 根据Id值删除会员
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public HXResult deleteMemberById(String ids) {

		try {
			String[] idStrings = ids.split(",");
			for (String id : idStrings) {
				memberService.deleteEntityById(GeneralUserEntity.class, id);
			}

			return HXResult.ok("删除会员成功！");
		} catch (Exception e) {
			e.printStackTrace();
			return HXResult.build(500, "服务器发生错误，删除会员数据失败！");
		}

	}

	/**
	 * 更新会员信息
	 * 
	 * @param hxuser
	 * @return
	 */
	@RequestMapping("/update")
	@ResponseBody
	public HXResult updateMemberById(HXUserForm hxuser) {

		GeneralUserEntity member = new GeneralUserEntity();
		MyBeanUtils.copyBeanNotNull2Bean(hxuser, member);

		try {
			memberService.saveOrUpdate(member);
			return HXResult.ok("更新用户数据成功！");

		} catch (Exception e) {
			e.printStackTrace();
			return HXResult.build(500, "服务器发生错误，更新会员数据失败！");
		}
	}

	/**
	 * 在后台添加用户操作
	 * 
	 * @param hxuser
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public HXResult addMember(HXUserForm hxuser) {

		GeneralUserEntity member = new GeneralUserEntity();
		MyBeanUtils.copyBeanNotNull2Bean(hxuser, member);
		member.setCheckstatus(45);

		// 是否删除 0 可用 ， 1 删除
		member.setIsDelete(0);
		// Date joinTime = member.getJoinDate();
		// member.setUpdateInfoTime(joinTime);

		member.setIsupdatepwd(0);

		// 设置更新时间
		Date date = new Date();
		member.setUpdateInfoDate(date);

		// 密码加密
		String pwdStr = PasswordUtil.encrypt(member.getPwd(), PasswordUtil.str, PasswordUtil.getStaticSalt());
		member.setPwd(pwdStr);

		try {
			memberService.saveOrUpdate(member);

			return HXResult.ok("添加会员成功！");

		} catch (Exception e) {
			e.printStackTrace();
			return HXResult.ok("服务器发生错误，新增会员数据失败！");
		}

	}

	@RequestMapping("/registerCheck")
	@ResponseBody
	public HXResult registerCheck(String id, Integer status) {
		try {
			GeneralUserEntity user = memberService.getEntity(GeneralUserEntity.class, id);
			// 审核通过操作
			if (status == 1) {
				user.setCheckstatus(StatusCode.SC_10_YES);
				memberService.saveOrUpdate(user);
				return HXResult.ok("操作成功，已经审核用户通过！");
				// 审核不通过操作
			} else if (status == 0) {
				user.setCheckstatus(StatusCode.SC_10_NO);
				memberService.saveOrUpdate(user);
				return HXResult.ok("操作成功，已经审核用户不通过！");
			} else if (status == 3) {
				user.setCheckstatus(StatusCode.SC_1);
				memberService.saveOrUpdate(user);
				return HXResult.ok("操作成功，已经还原用户状态！");
			}
			return HXResult.ok("系统服务异常，联系系统管理人员！");
		} catch (Exception e) {
			return HXResult.build(500, "服务器发生了异常，操作失败！");
		}
	}

	@RequestMapping("/file1Check")
	@ResponseBody
	public HXResult file1Check(String id, Integer status) {
		try {
			GeneralUserEntity user = memberService.getEntity(GeneralUserEntity.class, id);
			// 审核通过操作
			if (status == 1) {
				user.setCheckstatus(StatusCode.SC_25_YES);
				memberService.saveOrUpdate(user);
				return HXResult.ok("操作成功，已经审核用户通过！");
				// 审核不通过操作
			} else if (status == 0) {
				user.setCheckstatus(StatusCode.SC_25_NO);
				memberService.saveOrUpdate(user);
				return HXResult.ok("操作成功，已经审核用户不通过！");
			}
			return HXResult.ok("系统服务异常，联系系统管理人员！");
		} catch (Exception e) {
			return HXResult.build(500, "服务器发生了异常，操作失败！");
		}
	}

	@RequestMapping("/file2Check")
	@ResponseBody
	public HXResult file2Check(String id, Integer status) {
		try {
			GeneralUserEntity user = memberService.getEntity(GeneralUserEntity.class, id);
			// 审核通过操作
			if (status == 1) {
				user.setCheckstatus(StatusCode.SC_40_YES);
				memberService.saveOrUpdate(user);
				return HXResult.ok("操作成功，已经审核用户通过！");
				// 审核不通过操作
			} else if (status == 0) {
				user.setCheckstatus(StatusCode.SC_40_NO);
				memberService.saveOrUpdate(user);
				return HXResult.ok("操作成功，已经审核用户不通过！");
			}
			return HXResult.ok("系统服务异常，联系系统管理人员！");
		} catch (Exception e) {
			return HXResult.build(500, "服务器发生了异常，操作失败！");
		}
	}

	/**
	 * 发放证书操作
	 * 
	 * @param id
	 * @return
	 */

	@RequestMapping("/diploma")
	@ResponseBody
	public HXResult diploma(String id) {
		try {
			GeneralUserEntity user = memberService.getEntity(GeneralUserEntity.class, id);
			// 审核通过操作
			user.setCheckstatus(StatusCode.SC_45);
			// 将用户更改为一般会员
			user.setLevelclass(1);
			memberService.saveOrUpdate(user);
			return HXResult.ok("操作成功！");
			// 审核不通过操作

		} catch (Exception e) {
			return HXResult.build(500, "服务器发生了异常，操作失败！");
		}
	}

	/**
	 * 确认缴费
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/makeSurePay")
	@ResponseBody
	public HXResult makeSurePay(String id) {
		try {
			GeneralUserEntity user = memberService.getEntity(GeneralUserEntity.class, id);
			// 审核通过操作
			user.setCheckstatus(StatusCode.SC_34);
			// 将用户更改为一般会员
			memberService.saveOrUpdate(user);
			return HXResult.ok("操作成功！");
			// 审核不通过操作

		} catch (Exception e) {
			return HXResult.build(500, "服务器发生了异常，操作失败！");
		}
	}

	/**
	 * 管理员登录
	 * 
	 * @param session
	 * @param checkcode
	 * @param model
	 * @return
	 */
	@RequestMapping("/login")
	public String adminUserLogin(HttpSession session, String checkcode, AdminEntity model) {

		// 获取生成的验证码
		String key = (String) session.getAttribute("key");

		// 判断用户输入的验证码是否正确
		if (StringUtils.isNotBlank(checkcode) && checkcode.equals(key)) {
			// 验证码正确
			// 获得当前用户对象
			Subject subject = SecurityUtils.getSubject();
			String password = model.getPassword();

			// 对管理员用户的密码进行加密操作
			String passwrod = PasswordUtil.encrypt(password, PasswordUtil.str, PasswordUtil.getStaticSalt());
			// 构造一个用户名密码令牌
			AuthenticationToken token = new UsernamePasswordToken(model.getUsername(), password);
			try {

				subject.login(token);
			} catch (UnknownAccountException e) {
				e.printStackTrace();
				return "redirect:/index.jsp";
			} catch (Exception e) {
				e.printStackTrace();
				return "redirect:/index.jsp";
			}
			// 获取认证信息对象中存储的User对象
			AdminEntity user = (AdminEntity) subject.getPrincipal();
			// 用户登录登录成功
			session.setAttribute("loginUser", user);
			return "redirect:/home.jsp";
		} else {
			return "redirect:/index.jsp";
		}
	}

	@Autowired
	private IFileService fileService;
	@Autowired
	private IFileUserService fileUserServcie;

	/**
	 * 通过用户id，和文件种类查询文件
	 * 
	 * @param id
	 * @param
	 * @return
	 */

	@RequestMapping("/filelist")
	@ResponseBody
	public EasyUIDataGridResult getUserList(String id, String filetype) {
		// 通过id查询用户
		// GeneralUserEntity userEntity =
		// this.sysService.get(GeneralUserEntity.class,id);
		AdminMemberForm adminMemberForm = new AdminMemberForm();
		adminMemberForm.setStatus(filetype);
		adminMemberForm.setUid(id);
		CriteriaQuery cq = adminMemberForm.getCriteriaQuery();
		List<HxFileUser> fileUsers = fileUserServcie.list(cq);

		List<FileVo> fileVos = new ArrayList<>();
		for (HxFileUser fileUser : fileUsers) {
			FileVo fileVo = new FileVo();
			fileVo.copyEntity(fileUser.getHxFile());
			fileVos.add(fileVo);
		}
		EasyUIDataGridResult result = new EasyUIDataGridResult();

		result.setRows(fileVos);
		result.setTotal(fileVos.size());
		/*
		 * EasyUIDataGridResult result = new EasyUIDataGridResult();
		 * 
		 * List<HxFileUser> list2 =
		 * fileUserServcie.findByProperty(HxFileUser.class, "hxUser.id", id);
		 * 
		 * List<FileVo> list = new ArrayList<>(); for (HxFileUser hxFileUser :
		 * list2) {
		 * 
		 * FileVo hxFile = sysService.get(FileVo.class,
		 * hxFileUser.getHxFile().getId()); list.add(hxFile); }
		 * 
		 * result.setRows(list); result.setTotal(list.size());
		 */

		// String id, Status status
		// 执行sql语句
		// String sql = "SELECT hx_file.id 'id',hx_file.NAME
		// 'name',hx_file.createtime 'receatetime' FROM `hx_file` RIGHT JOIN
		// hx_file_user ON hx_file.id = hx_file_user.fid RIGHT JOIN hx_user ON
		// hx_user.id = hx_file_user.userid WHERE hx_file.filetype = '" + status
		// + "' and hx_user.id = '" + id + "'";
		// sysService.executeSql(sql, status, id);
		// List<HxFile> list = fileService.findListbySql(sql);

		// EasyUIDataGridResult result = new EasyUIDataGridResult();
		// result.setRows(list);
		// result.setTotal(list.size());
		// TODO 返回json数据有问题
		return result;

	}

	/**
	 * 
	 * 通过文件id下载文件
	 * 
	 * @throws Exception
	 */

	@RequestMapping(value = "/file/down")
	public void download(HttpServletResponse res, String fileId) throws IOException {
		/*
		 * 根据文件id，查找用户名
		 */
		AdminMemberForm adminMemberForm = new AdminMemberForm();
		adminMemberForm.setFid(fileId);
		CriteriaQuery cq = adminMemberForm.getCriteriaQuery();
		List<HxFileUser> fileUsers = fileUserServcie.list(cq);

		HxFileUser hxFileUser = fileUsers.get(0);
		String userid = hxFileUser.getHxUser().getId();

		GeneralUserEntity userEntity = sysService.get(GeneralUserEntity.class, userid);
		String realname = userEntity.getRealname();

		OutputStream os = res.getOutputStream();
		try {
			// 通过文件id查找文件名称和下载路径
			HxFile hxFile = fileUserServcie.get(HxFile.class, fileId);

			Integer filetype = hxFile.getFiletype();
			String fileType = null;
			if (filetype == 1) {
				fileType = "-入会申请资料-";
			} else if (filetype == 2) {
				fileType = "-入会协议资料-";
			} else if (filetype == 3) {
				fileType = "-回执单-";

			}

			// 下载的文件路径
			String path = hxFile.getDownloadUrl();

			File file = new File(path);
			HttpHeaders headers = new HttpHeaders();
			// 为了解决中文名称乱码问题

			/*
			 * 下载问件时，提示的文件名称
			 */

			String downloadName = realname + fileType + hxFile.getName();

			String fileName = new String(downloadName.getBytes("UTF-8"), "iso-8859-1");
			res.reset();
			res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
			res.setContentType("application/octet-stream; charset=utf-8");
			os.write(FileUtils.readFileToByteArray(file));
			os.flush();
		} finally {
			if (os != null) {
				os.close();
			}
		}
	}


	/*
	 * 管理员相关页面跳转
	 */
	@RequestMapping("/{path}")
	public String goPath(@PathVariable String path) {
		return "admin/member/" + path;
	}

}
